package mq.config;

import lombok.extern.slf4j.Slf4j;
import mq.dao.mapper.MqMessageAbnormalMapper;
import mq.domain.MqMessageAbnormal;
import mq.service.IMqMailService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

/**
 * @description: 生产者发送给交换机的回调函数
 * @author: zk
 * @since: 2022-08-15 15:09
 */
@Slf4j
@Component
public class MyConfirmCallback implements RabbitTemplate.ConfirmCallback {
    @Resource
    private MqMessageAbnormalMapper mqMessageAbnormalMapper;
    @Resource
    private IMqMailService mqMailService;
    @Resource
    private MessageConverter messageConverter;

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("生产者发送给交换机的回调函数:correlationData={},ack={},cause={}",correlationData,ack,cause);
        if (ack) {
            // 消息签收成功
            return;
        }
        Message message = correlationData.getReturnedMessage();
        if (Objects.isNull(message)) {
            return;
        }
        Optional<String> messageId = Optional.ofNullable(message)
                .map(Message::getMessageProperties)
                .map(MessageProperties::getMessageId);

        Object obj = messageConverter.fromMessage(message);
        if (obj instanceof MqMessageAbnormal) {
            // 签收失败消息入库
            MqMessageAbnormal mqMessageAbnormal = (MqMessageAbnormal) obj;
            //mqMessageAbnormal.setMessageId(messageId.orElseGet(() -> String.valueOf(SnowflakeIdWorker.nextID())));
            //mqMessageAbnormal.setStatus(MqMessageAbnormal.STATUS_FAIL);
            //mqMessageAbnormal.setType(MqMessageAbnormal.TYPE_EXCHANGE);
            //mqMessageAbnormal.setCause(cause);
            //mqMessageAbnormal.setCreateTime(new Date());
            //mqMessageAbnormal.setUpdateTime(new Date());
            //BeanUtils.notNull(mqMessageAbnormal);
            mqMessageAbnormalMapper.insertOrUpdateBatch(Arrays.asList(mqMessageAbnormal));
        }

        // 邮件预警
        //messageId.ifPresent(s -> mqMailService.addRecord(s, MqMailServiceImpl.TYPE_CONFIRM_CALL_BACK));
    }
}
